package com.example.recyclerViewDemo

import android.util.Log
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView

/**
 * @Author Xzh
 * @Date 2024/12/16
 * @Description
 */
class MyLayoutManager : RecyclerView.LayoutManager() {
    companion object{
        const val TAG = "MyLayoutManager"
    }

    /**
     * 创建HorizontalLayoutManager 继承于LayoutManager，必须重写方法generateDefaultLayoutParams()，默认返回RecyclerView.LayoutParams
     */
    override fun generateDefaultLayoutParams(): RecyclerView.LayoutParams {
        return RecyclerView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT)
    }

    override fun onLayoutChildren(recycler: RecyclerView.Recycler, state: RecyclerView.State?) {
        //分离并且回收当前附加的所有View
        //将所有的子View先Detach掉，放入到Scrap缓存中。
       detachAndScrapAttachedViews(recycler)
        if (itemCount == 0) {
            return
        }

        var offsetX = 0

        //绘制并添加View
        for (i in 0 until itemCount){
            //使用 recycler.getViewForPosition(i) 从 recycler 获取一个视图，该视图表示当前位置的项目。
            val view = recycler.getViewForPosition(i)
            //使用 addView(view) 将视图添加到 RecyclerView 中
            addView(view)
            //使用 measureChildWithMargins(view, 0, 0) 测量视图的尺寸。
            measureChildWithMargins(view,0,0)
            val viewWidth = getDecoratedMeasuredWidth(view)
            val viewHeight = getDecoratedMeasuredHeight(view)
            //使用 layoutDecorated(view, offsetX, 0, offsetX + viewWidth, viewHeight) 在 RecyclerView 中布局视图。视图的左上角坐标为 (offsetX, 0)，右下角坐标为 (offsetX + viewWidth, viewHeight)
            layoutDecorated(view,offsetX,0,offsetX+viewWidth,viewHeight)
            offsetX+=viewWidth
        }
    }


    /**
     * 是否横向滚动
     */
    override fun canScrollHorizontally(): Boolean {
        return true
    }

    override fun scrollHorizontallyBy(
        dx: Int,
        recycler: RecyclerView.Recycler?,
        state: RecyclerView.State?
    ): Int {
        Log.e(TAG, "dx-----:$dx " )

        offsetChildrenHorizontal(dx * -1)
        return dx
    }

    /**
     * 是否垂直滚动
     */
    override fun canScrollVertically(): Boolean {
        return true
    }

    override fun scrollVerticallyBy(
        dy: Int,
        recycler: RecyclerView.Recycler?,
        state: RecyclerView.State?
    ): Int {
        Log.e(TAG, "dy-----:$dy " )

        offsetChildrenVertical(dy * -1)
        return dy
    }


}